package leecode

func numIslands(grid [][]byte) int {
	var dfs func(grid [][]byte, row, column int)
	dfs = func(grid [][]byte, row, column int) {
		//判断是否在范围内
		if !isArea(grid, row, column) {
			return
		}
		if grid[row][column] != '1' {
			//如果不是岛屿,停止递归
			return
		}
		//将遍历过的岛屿标记位2
		grid[row][column] = '2'
		//上
		dfs(grid, row-1, column)
		//下
		dfs(grid, row+1, column)
		//左
		dfs(grid, row, column-1)
		//右
		dfs(grid, row, column+1)
	}
	var result int
	for i := 0; i < len(grid); i++ {
		for j := 0; j < len(grid[0]); j++ {
			if grid[i][j] == '1' {
				dfs(grid, i, j)
				result++
			}
		}
	}
	return result
}

func isArea(grid [][]byte, row, column int) bool {
	//判断坐标是否在岛屿中
	return 0 <= row && row < len(grid) && 0 <= column && column < len(grid[0])
}
